import 'package:flutter/material.dart';
import 'package:shenling_project/home/components/taskItem.dart';
import 'package:shenling_project/utils/request.dart';
import 'package:shenling_project/utils/toast.dart';
import '../utils/eventBus.dart';

class Tobepickedup extends StatefulWidget {
  const Tobepickedup({super.key});

  @override
  State<Tobepickedup> createState() => _TobepickedupState();
}

class _TobepickedupState extends State<Tobepickedup> {
//任务列表
  Map taskList = {
    'counts': 0,
    'page': 1,
    'pageSize': 10,
    'pages': 1,
    'items': List
  };
  List item = [];

  //是否加载中
  bool _isLoading = false;
  //页码
  int _page = 1;

  //listview组件控制器
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    //获取数据列表
    _getDataList();
    event.on<GetHomeData>().listen((e) {
      _getDataList();
    });

    _scrollController.addListener(listviewScrollListener);
  }

//listview滚动事件
  listviewScrollListener() async {
    //触底
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      // print('触底了');
      if (_isLoading) return;
      try {
        setState(() {
          _page = _page + 1;
        });
        final res = await http.request('get', '/driver/tasks/list', null, {
          'page': _page,
          'pageSize': 10,
          'startTime': '2022-06-12',
          'endTime': '2025-07-02',
          'status': 1
        });

        setState(() {
          taskList = res['data'];
          taskList['pages'] = res['data']['pages'];
          item.addAll(res['data']['items']);
        });
        // ToastUtil.showInfo('加载成功');

        // ToastUtil.showSuccess('当前页码是:$_page,接口的页面是${res['data']['pages']}');
        if (_page == res['data']['pages']) {
          return ToastUtil.showInfo('已经没有更多数据了!');
        }
      } catch (e) {
        ToastUtil.showInfo('已经没有更多数据了!');
      }
    }
  }

//获取数据列表
  _getDataList() async {
    try {
      setState(() {
        _isLoading = true;
      });
      final res = await http.request('get', '/driver/tasks/list', null, {
        'page': _page,
        'pageSize': 10,
        'startTime': '2022-06-12',
        'endTime': '2025-07-02',
        'status': 1
      });
      Future.delayed(const Duration(seconds: 1), () {
        setState(() {
          taskList = res['data'];
          item = res['data']['items'];
          _isLoading = false;
        });
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _refresh() async {
    setState(() {
      _page = 1;
    });
    await _getDataList();
    ToastUtil.showSuccess('刷新成功');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        // 设置主体内容
        body: _isLoading
            ? const Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    CircularProgressIndicator(),
                    SizedBox(
                      height: 10,
                    ),
                    Text('加载中...'),
                  ],
                ),
              )
            : RefreshIndicator(
                onRefresh: _refresh,
                child: ListView.separated(
                    controller: _scrollController,
                    itemBuilder: (ctx, index) {
                      return Taskitem(
                        item: item[index],
                      );
                    },
                    separatorBuilder: (ctx, idnex) {
                      return const SizedBox(
                        height: 2,
                      );
                    },
                    itemCount: item.length),
              ));
  }
}
